/**
 * 2017年1月6日
 * 建立依赖于 connector服务器的 httpServer
 */

var http = require('http');
var url = require("url");
var querystring = require('querystring');


var router = require('./../util/routeUtil');

var log = console.log;

var connectService = function (app, opts) {
    log('connectService start-----------------------------');
    var httpPort = opts.httpPort;
    this.app = app;
    var self = this;
    // 使用sessionService来获取用户是否在线的状态
    // 如果connector 挂掉了，那就没法进行游戏了，用户肯定不在游戏中
    this.sessionService = self.app.get('sessionService');
    // log(this.sessionService);

    self.server = http.createServer(function (req, res) {

        var pathname = url.parse(req.url).pathname;  /// pathname 在url里面
        // 关闭node.js 默认访问 favicon.ico
        if (!pathname.indexOf('/favicon.ico')) {
            return;
        }
        req.setEncoding('utf-8');
        var postData = '';
        req.on('data', function (data) {
            console.log('get post data ------------------------------------');
            postData += data;
        });
        req.on('end', function () {
            log("Request for " + pathname + ", postData:" + postData);
            // log('req.................');
            // log(req.connection);
            self.route(req.url, pathname, postData, function (err, rel) {
                var ret = null;
                if (err) {
                    ret = { err: err };
                }
                else {
                    ret = { rel: rel };
                }
                ret = JSON.stringify(ret);
                res.write(ret);
                res.end();
            });
            // router.httpRoute(self.app, handle, pathname, postData, req.connection.remoteAddress, function (err, result) {
            //     var backData = JSON.stringify(result);
            //
            //     logger.debug("Response for " + pathname + ":" + backData);
            //     res.write(backData);
            //     res.end();
            // });
        });
    });

    console.log("gate server start port = " + httpPort);
    this.server.listen(httpPort);
    // log(this.server);
};

var pro = connectService.prototype;

pro.route = function (_url, pathname, postData, cb) {
    log('route............');
    log(_url);
    log(url.parse(_url, true).query);
    log(pathname);

    if (postData) {
        postData = querystring.parse(postData);
    }

    var query = url.parse(_url, true).query;
    for (var k in query) {
        if (!postData) {
            postData = {};
        }
        if (!postData[k]) {
            postData[k] = query[k];
        }
    }
    pathname = pathname.substring(1);
    if (typeof this[pathname] === 'function') {
        this[pathname](postData, cb);
    }
    else {
        cb('request path not Exists!');
    }
};

// 检查用户是否在线
pro.checkPlayerOnline = function (data, cb) {
    log('checkPlayerOnline.............');
    var sessionService = this.sessionService;
    // log(sessionService);
    // // log()
    if (sessionService.getByUid(data.playerId)) {
        cb(null, 1);
    }
    else {
        cb(null, 0);
    }
};

module.exports = connectService;
